package xyz.xwls.bootadmin.sys.service.impl;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import xyz.xwls.bootadmin.sys.domain.Auth;
import xyz.xwls.bootadmin.sys.domain.Tree;
import xyz.xwls.bootadmin.sys.repository.AuthRepository;
import xyz.xwls.bootadmin.sys.service.AuthService;
import xyz.xwls.bootadmin.sys.vo.AuthVo;
import xyz.xwls.bootadmin.util.BuildTree;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author WZW
 * @date 2020/4/20
 */
@Service
public class AuthServiceImpl implements AuthService {

    @Autowired
    private AuthRepository authRepository;

    public static AuthVo convert(Auth auth) {
        AuthVo authVo = new AuthVo();
        BeanUtils.copyProperties(auth, authVo);
        return authVo;
    }

    public static List<AuthVo> convert(List<Auth> authList) {
        return authList.stream().map(AuthServiceImpl::convert).collect(Collectors.toList());
    }

    @Override
    public List<Tree<AuthVo>> getAuthTree() {
        List<Tree<AuthVo>> trees = new ArrayList<>();
        List<Auth> authList = authRepository.findAll();
        authList.forEach(auth -> {
            Tree<AuthVo> tree = new Tree<>();
            tree.setId(auth.getId().toString());
            tree.setParentId(auth.getParentId().toString());
            tree.setText(auth.getName());
            tree.setObject(convert(auth));
            trees.add(tree);
        });
        return BuildTree.buildList(trees, "0");
    }
}
